import {
  PlusOutlined,
  DeleteOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons';
import { Button, Popconfirm, message } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { pagePost, addPost, updatePost, removePost } from '@/services/system/post';
import type { PostItem, PostParams } from '@/services/system/types';
import { ProFormText, ProFormTextArea, ProFormDigit, ProFormSelect } from '@ant-design/pro-form';
import EditForm from '@/components/EditForm';
import { getDictValues } from '@/services/system/dictValue';
import { PostColumns } from './columns';
import SzhomeTable from '@/components/Custom/SzhomeTable';
/**
 * 添加岗位
 *
 * @param fields
 */
const handleAdd = async (fields: PostItem) => {
  const hide = message.loading('正在新增岗位');

  try {
    await addPost({ ...fields });
    hide();
    message.success('岗位添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('岗位添加失败，请重试！');
    return false;
  }
};

/**
 * 更新岗位
 *
 * @param fields
 */
const handleUpdate = async (fields: PostItem, currentRow?: PostItem) => {
  const hide = message.loading('正在更新岗位');

  try {
    await updatePost({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('岗位更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('岗位更新失败，请重试');
    return false;
  }
};

/**
 * 删除岗位
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: PostItem[]) => {
  const hide = message.loading('正在删除岗位');
  if (!selectedRows) return true;

  try {
    await removePost(selectedRows.map((row) => row.id));
    hide();
    message.success('岗位删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('岗位删除失败，请重试');
    return false;
  }
};

const statusList = await getDictValues('disable.enable');

const Post: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<PostItem>();
  const [selectedRowsState, setSelectedRows] = useState<PostItem[]>([]);

  /** 国际化配置 */

  const columns: ProColumns<PostItem>[] = [
    ...PostColumns,
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      width: 220,
      render: (_, record) => [
        <a
          key={'edit-' + record.id}
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key={'delete-' + record.id}
          title="您确定要删除此岗位吗？"
          onConfirm={async () => {
            await handleRemove([record]);
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="Yes"
          cancelText="No"
        >
          <a key="remove">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <SzhomeTable<PostItem, PostParams>
        actionRef={actionRef}
        request={pagePost}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增
          </Button>,

          <Popconfirm
            key={'batch_remove'}
            disabled={selectedRowsState?.length == 0}
            title={'您确定要删除已选' + selectedRowsState?.length + '条数据吗？'}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button key="batch_remove" danger disabled={selectedRowsState?.length == 0}>
              <DeleteOutlined />
              删除
            </Button>
          </Popconfirm>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudDownloadOutlined /> 导出
          </Button>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudUploadOutlined /> 导入
          </Button>,
        ]}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      <EditForm
        visible={createModalVisible}
        name="岗位"
        model={currentRow || { id: undefined }}
        onAdd={handleAdd}
        onUpdate={handleUpdate}
        afterEdit={() => {
          setCurrentRow(undefined);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={handleModalVisible}
      >
        <ProFormText name="id" hidden={true} />
        <ProFormText label="名称" name="name" required colProps={{ span: 12 }} />
        <ProFormText label="编码" name="code" required colProps={{ span: 12 }} />
        <ProFormSelect
          label="状态"
          name="gender"
          required
          colProps={{ xs: 12 }}
          valueEnum={statusList}
        />
        <ProFormDigit
          required
          label="顺序"
          name="rank"
          min={1}
          initialValue={1}
          fieldProps={{ precision: 0 }}
          colProps={{ span: 12 }}
        />
        <ProFormTextArea label="备注" name="remark" />
      </EditForm>
    </PageContainer>
  );
};

export default Post;
